<template>
  <div class="user-manage-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.departmentId" placeholder="请选择部门" clearable>
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable>
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" label="#" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="realName" label="姓名" min-width="120" />
        <el-table-column prop="phone" label="手机号码" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="150" />
        <el-table-column prop="departmentName" label="部门" min-width="120" />
        <el-table-column prop="positionName" label="职位" min-width="120" />
        <el-table-column prop="roleName" label="角色" min-width="120">
          <template #default="scope">
            <el-tag v-for="role in scope.row.roles" :key="role.id" class="role-tag">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="primary" link @click="handleResetPassword(scope.row)">
              <el-icon><Key /></el-icon>重置密码
            </el-button>
            <el-button
              type="primary"
              link
              :disabled="scope.row.username === 'admin'"
              @click="handleToggleStatus(scope.row)"
            >
              <el-icon><CircleCheck v-if="scope.row.status === 0" /><CircleClose v-else /></el-icon>
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" show-password placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="userForm.departmentId" placeholder="请选择部门">
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="positionId">
          <el-select v-model="userForm.positionId" placeholder="请选择职位">
            <el-option
              v-for="item in positionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPasswordForm.password" type="password" show-password placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Key, CircleCheck, CircleClose } from '@element-plus/icons-vue'

// 表单引用
const userFormRef = ref(null)
const resetPasswordFormRef = ref(null)

// 表格加载状态
const tableLoading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const resetPasswordDialogVisible = ref(false)
const currentUserId = ref(null)

// 搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  departmentId: '',
  roleId: '',
  status: ''
})

// 用户表单
const userForm = reactive({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  departmentId: '',
  positionId: '',
  roleIds: [],
  status: 1
})

// 重置密码表单
const resetPasswordForm = reactive({
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  positionId: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 重置密码表单验证规则
const resetPasswordFormRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    username: 'admin',
    realName: '管理员',
    phone: '13800138000',
    email: 'admin@tms.com',
    departmentId: 1,
    departmentName: '信息技术部',
    positionId: 1,
    positionName: '系统管理员',
    roles: [{ id: 1, name: '超级管理员' }],
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 2,
    username: 'zhangsan',
    realName: '张三',
    phone: '13800138001',
    email: 'zhangsan@tms.com',
    departmentId: 2,
    departmentName: '运输部',
    positionId: 2,
    positionName: '调度员',
    roles: [{ id: 2, name: '调度员' }],
    status: 1,
    createTime: '2025-01-02 00:00:00'
  },
  {
    id: 3,
    username: 'lisi',
    realName: '李四',
    phone: '13800138002',
    email: 'lisi@tms.com',
    departmentId: 3,
    departmentName: '财务部',
    positionId: 3,
    positionName: '财务专员',
    roles: [{ id: 3, name: '财务人员' }],
    status: 1,
    createTime: '2025-01-03 00:00:00'
  },
  {
    id: 4,
    username: 'wangwu',
    realName: '王五',
    phone: '13800138003',
    email: 'wangwu@tms.com',
    departmentId: 4,
    departmentName: '客服部',
    positionId: 4,
    positionName: '客服专员',
    roles: [{ id: 4, name: '客服人员' }],
    status: 0,
    createTime: '2025-01-04 00:00:00'
  }
])

// 下拉选项
const departmentOptions = ref([
  { id: 1, name: '信息技术部' },
  { id: 2, name: '运输部' },
  { id: 3, name: '财务部' },
  { id: 4, name: '客服部' },
  { id: 5, name: '人力资源部' }
])

const positionOptions = ref([
  { id: 1, name: '系统管理员' },
  { id: 2, name: '调度员' },
  { id: 3, name: '财务专员' },
  { id: 4, name: '客服专员' },
  { id: 5, name: '人力资源专员' },
  { id: 6, name: '部门经理' }
])

const roleOptions = ref([
  { id: 1, name: '超级管理员' },
  { id: 2, name: '调度员' },
  { id: 3, name: '财务人员' },
  { id: 4, name: '客服人员' },
  { id: 5, name: '普通用户' }
])

// 加载用户列表
const loadUserList = async () => {
  tableLoading.value = true
  try {
    // 实际项目中应该调用API获取用户列表
    // const { data } = await getUserList({
    //   ...searchForm,
    //   page: pagination.currentPage,
    //   pageSize: pagination.pageSize
    // })
    // tableData.value = data.list
    // pagination.total = data.total
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用模拟数据
    pagination.total = tableData.value.length
    
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadUserList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  resetUserForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetUserForm()
  
  // 填充表单数据
  userForm.id = row.id
  userForm.username = row.username
  userForm.realName = row.realName
  userForm.phone = row.phone
  userForm.email = row.email
  userForm.departmentId = row.departmentId
  userForm.positionId = row.positionId
  userForm.roleIds = row.roles.map(role => role.id)
  userForm.status = row.status
  
  dialogVisible.value = true
}

// 重置用户表单
const resetUserForm = () => {
  Object.keys(userForm).forEach(key => {
    if (key === 'status') {
      userForm[key] = 1
    } else if (key === 'roleIds') {
      userForm[key] = []
    } else {
      userForm[key] = ''
    }
  })
  
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 实际项目中应该调用API添加用户
          // await addUser(userForm)
          ElMessage.success('添加用户成功')
        } else {
          // 实际项目中应该调用API更新用户
          // await updateUser(userForm)
          ElMessage.success('更新用户成功')
        }
        
        dialogVisible.value = false
        loadUserList()
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('保存用户失败')
      }
    }
  })
}

// 重置密码
const handleResetPassword = (row) => {
  currentUserId.value = row.id
  resetPasswordForm.password = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordDialogVisible.value = true
}

// 提交重置密码
const submitResetPassword = async () => {
  if (!resetPasswordFormRef.value) return
  
  await resetPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 实际项目中应该调用API重置密码
        // await resetUserPassword({
        //   userId: currentUserId.value,
        //   password: resetPasswordForm.password
        // })
        
        ElMessage.success('重置密码成功')
        resetPasswordDialogVisible.value = false
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置密码失败')
      }
    }
  })
}

// 启用/禁用用户
const handleToggleStatus = (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  const newStatus = row.status === 1 ? 0 : 1
  
  ElMessageBox.confirm(
    `确定要${action}用户 "${row.realName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中应该调用API更新用户状态
        // await updateUserStatus({
        //   userId: row.id,
        //   status: newStatus
        // })
        
        // 更新本地数据
        row.status = newStatus
        
        ElMessage.success(`${action}用户成功`)
      } catch (error) {
        console.error(`${action}用户失败:`, error)
        ElMessage.error(`${action}用户失败`)
      }
    })
    .catch(() => {})
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-tag {
  margin-right: 5px;
}
</style>
